﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008, 2009 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace EngineOfEvermore.Common
{
    public static class Util
    {
        public const float STANDARD_EPSILON = 0.001f;
        public const float NEGATIVE_STANDARD_EPSILON = -STANDARD_EPSILON;
        public const float FLOAT_PI = (float) Math.PI;

        /// <summary>
        /// Compares two floats allowing for an error of epsilon.
        /// </summary>
        public static bool EpsilonEquals( this float a, float b, float epsilon )
        {
            Debug.Assert( epsilon > 0.0f );

            float diff = a - b;
            return ( diff <= epsilon ) && ( diff >= -epsilon );
        }

        /// <summary>
        /// Compares two floats allowing for an error of STANDARD_EPSILON.
        /// </summary>
        public static bool EpsilonEquals( this float a, float b )
        {
            float diff = a - b;
            return ( diff <= STANDARD_EPSILON ) && ( diff >= NEGATIVE_STANDARD_EPSILON );
        }

        /// <summary>
        /// Compares a float to zero allowing for an error of epsilon.
        /// </summary>
        public static bool EpsilonIsZero( this float a, float epsilon )
        {
            return ( a <= epsilon ) && ( a >= -epsilon );
        }

        /// <summary>
        /// Compares a float to zero allowing for an error of STANDARD_EPSILON.
        /// </summary>
        public static bool EpsilonIsZero( this float a )
        {
            return ( a <= STANDARD_EPSILON ) && ( a >= NEGATIVE_STANDARD_EPSILON );
        }

        /// <summary>
        /// Sorts an array using the insertion sort algorithm.
        /// </summary>
        public static void InsertionSort<T>( this T[] array, IComparer<T> comparer )
        {
            for ( int i = 1; i < array.Length; ++i ) 
            {
                T value = array[i];
                int j = i-1;

                while ( j >= 0 && comparer.Compare( array[j], value ) > 0 )
                {
                    array[j + 1] = array[j];
                    --j;
                }

                array[j+1] = value;
            }
        }

        /// <summary>
        /// Sorts an array using the insertion sort algorithm.
        /// </summary>
        public static void InsertionSort<T>( this T[] array ) where T : IComparable<T>
        {
            for ( int i = 1; i < array.Length; ++i )
            {
                T value = array[i];
                int j = i - 1;

                while ( j >= 0 && array[j].CompareTo( value ) > 0 )
                {
                    array[j + 1] = array[j];
                    --j;
                }

                array[j + 1] = value;
            }
        }

        /// <summary>
        /// Sorts a linked list using the insertion sort algorithm.
        /// </summary>
        public static void InsertionSort<T>( this LinkedList<T> list ) where T : IComparable<T>
        {
            if ( list.First == null || list.First.Next == null )
                return;

            LinkedListNode<T> node = list.First.Next;

            while ( node != null )
            {
                LinkedListNode<T> currentNode = node;
                node = currentNode.Next;

                LinkedListNode<T> walkNode = currentNode.Previous;

                while ( walkNode != null && 
                    currentNode.Value.CompareTo( walkNode.Value ) < 0 )
                {
                    walkNode = walkNode.Previous;
                }

                if ( walkNode == null )
                {
                    list.Remove( currentNode );
                    list.AddFirst( currentNode );
                }
                else
                {
                    list.Remove( currentNode );
                    list.AddAfter( walkNode, currentNode );
                }
            }
        }

        /// <summary>
        /// Finds the minimum and the maximum in a sequence.
        /// </summary>
        public static void FindMinMax<T>( this IEnumerable<T> values, out T min, out T max )
            where T : IComparable<T>
        {
            min = values.First();
            max = min;

            foreach( T value in values )
            {
                if ( value.CompareTo( min ) < 0 )
                {
                    min = value;
                }
                else if ( value.CompareTo( max ) > 0 )
                {
                    max = value;
                }
            }
        }

        /// <summary>
        /// Converts radians to degrees.
        /// </summary>
        public static float RadToDeg( float rad )
        {
            return rad * ( 180.0f / FLOAT_PI );
        }

        /// <summary>
        /// Converts degrees to radians.
        /// </summary>
        public static float DegToRad( float degrees )
        { 
            return degrees * ( FLOAT_PI / 180.0f );
        }

        /// <summary>
        /// Converts radians to degrees.
        /// </summary>
        public static double RadToDeg( double rad )
        {
            return rad * ( 180.0 / Math.PI );
        }

        /// <summary>
        /// Converts degrees to radians.
        /// </summary>
        public static double DegToRad( double degrees )
        {
            return degrees * ( Math.PI / 180.0 );
        }

        /// <summary>
        /// Returns true if the two enumeration contain the same items independent of their order.
        /// </summary>
        public static bool IsEquivalentTo<T>( this IEnumerable<T> c1, IEnumerable<T> c2 )
        {
            return ( !c1.Except( c2 ).Any() ) && ( !c2.Except( c1 ).Any() );
        }

        public static IEnumerable<T> Generate<T>( Func<T> factory, int count )
        {
            for ( int i = 0; i < count; ++i )
            {
                yield return factory.Invoke();
            }
        }
    }
	
    #if ENGINE_OF_EVERMORE_ENABLE_UNIT_TESTS
    namespace Test
    {
    	using NUnit.Framework;

		[TestFixture]
		public class TestUtils
		{
			[Test]
			public void TestEpsilonEqualsTrue()
			{
				bool result = Util.EpsilonEquals( 3.14f, 3.15f,0.1f );
				Assert.IsTrue( result );		 
			}
			
			[Test]
			public void TestEpsilonEqualsFalse()
			{
				bool result = Util.EpsilonEquals( 3.14f, 3.16f, 0.01f );
				Assert.IsFalse( result );
			}
			
			[Test]
			public void TestStandEpsilonEqualsTrue()
			{
				bool result = Util.EpsilonEquals( 3.141f, 3.1415f );
				Assert.IsTrue( result );
			}
			
			[Test]
			public void TestStandEpsilonEqualsFalse()
			{
				bool result = Util.EpsilonEquals( 3.141f, 3.1425f );
				Assert.IsFalse( result );
			}
			
			[Test]
			public void TestEpIsZeroTrue()
			{
				bool result = Util.EpsilonIsZero( 0.002f, 0.01f );
				Assert.IsTrue( result );
			}
			
			[Test]
			public void TestEpIsZeroFalse()
			{
				bool result = Util.EpsilonIsZero( 0.012f, 0.01f );
				Assert.IsFalse( result );
			}
			
			[Test]
			public void TestStandEpIsZeroTrue()
			{
				bool result = Util.EpsilonIsZero( 0.0005f );
				Assert.IsTrue( result );
			}
			
			[Test]
			public void TestStandEpIsZeroFalse()
			{
				bool result = Util.EpsilonIsZero( 0.05f );
				Assert.IsFalse( result );
			}
			
			[Test]
			public void TestInsertionSortArray1()
			{
				int[] testarr = { 4, -3, 20, 0, 2147483647 };
				int[] expectedarr = { -3, 0, 4, 20, 2147483647 };
				TestComparer testcomp = new TestComparer();
				
				Util.InsertionSort( testarr, testcomp );
				
				CollectionAssert.AreEqual( expectedarr, testarr );
			}
			
			[Test]
			public void TestInsertionSortArray2()
			{
				int[] testarr = { 4, -3, 20, 0, 2147483647 };
				int[] expectedarr = { -3, 0, 4, 20, 2147483647 };
				
				Util.InsertionSort( testarr );
				
				CollectionAssert.AreEqual( expectedarr, testarr );
			}
			
			[Test]
			public void TestInsertionSortLinkedList()
			{
				LinkedList<int> testlist = new LinkedList<int>();
				int[] testarr = { 4, -3, 20, 0, 2147483647 };
				int[] expectedarr = { -3, 0, 4, 20, 2147483647 };
				
				foreach ( int element in testarr )
				{
					testlist.AddFirst( element );
				}
				
				Util.InsertionSort( testlist );
				
				CollectionAssert.AreEqual( expectedarr, testlist.ToArray() );
			}
			
			[Test]
			public void TestInsertionSortLinkedListFail()
			{
				LinkedList<string> testlist = new LinkedList<string>();
		
				Util.InsertionSort( testlist );
				
				Assert.IsNotNull( testlist );
			}		
			
			[Test]
			public void TestFindMinMax()
			{
				int[] testArray = { 23, 9, 7, 13, 90, 0, -16 };
				int min, max;
				
				Util.FindMinMax( testArray, out min, out max );
	
				int[] resultArray = new int[2]{ min, max };
				int[] expectedArr = new int[2]{ -16, 90 };
				
				CollectionAssert.AreEqual( expectedArr, resultArray );
			}
			
			[Test]
			public void TestRadToDegFloat()
			{
				float rad = 1.5f * ( float ) Math.PI;
				float result = Util.RadToDeg( rad );
				Assert.AreEqual( 270, result );
			}
			
			[Test]
			public void TestDegToRadFloat()
			{
				float deg = 270.0f;
				float result = Util.DegToRad( deg );
				Assert.AreEqual( 1.5f * ( float ) Math.PI, result );
			}
			
		
			[Test]
			public void TestDegToRadDouble()
			{
				double degree = 270.0;
				double result = Util.DegToRad( degree );
				Assert.AreEqual( 1.5 * Math.PI, result );
			}
			
			[Test]
			public void TestRadToDegDouble()
			{
				double rad = 1.5 * Math.PI;
				double result = Util.RadToDeg( rad );
				Assert.AreEqual( 270, result );
			}

            [Test]
            public void TestIEnumerableIsEquivalentTo()
            {
                var e1 = new Object[] { new Object(), new Object(), new Object() };
                var eTrue = new Object[] { e1[2], e1[0], e1[1] };
                var eFalse = new Object[] { e1[0], e1[0], e1[1] };
                var eFalse2 = new Object[] { new Object(), new Object() };

                Assert.That( e1.IsEquivalentTo( eTrue ), Is.True );
                Assert.That( e1.IsEquivalentTo( eFalse ), Is.False );
                Assert.That( e1.IsEquivalentTo( eFalse2 ), Is.False );
            }

            [Test]
            public void TestGenerateEnumerable()
            {
                IEnumerable<int> range = Util.Generate( () => 42, 8 );

                Assert.That( range.Count(), Is.EqualTo( 8 ) );
                Assert.That( range.All( val => val == 42 ), Is.True );
            }
		}
		
		internal class TestComparer : IComparer<int>
		{
			public int Compare( int a, int b )
			{
				return a.CompareTo( b );
			}
		}
    }
    #endif
}
